package com.sky.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.OrderBusinessException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;
@Data
@AllArgsConstructor
@Slf4j
public class BaiDuMapUtil {
    public static String geocodingURL = "https://api.map.baidu.com/geocoding/v3?";
    public static String ridingURL = "https://api.map.baidu.com/direction/v2/riding?";
    private String AK;
    private String shopLocation;
    public void checkDistance(String destination) throws Exception {
        //获取店铺地理位置信息
        Map params = new LinkedHashMap<String, String>();
        params.put("address", shopLocation);
        params.put("output", "json");
        params.put("ak", AK);
        params.put("callback", "showLocation");
        String begin = requestGetAK(geocodingURL, params);
        begin = begin.replace("showLocation&&showLocation(", "");
        begin = begin.replace(")","");
        //获取目的地地理位置信息
        params.put("address", destination);
        String end = requestGetAK(geocodingURL, params);
        end = end.replace("showLocation&&showLocation(", "");
        end = end.replace(")","");
        //计算两地间的距离
        System.out.println("----------------begin---------------------");
        System.out.println(begin);
        System.out.println("----------------end---------------------");
        System.out.println(end);
        JSONObject jsonObject = JSONObject.parseObject(begin);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("商店地址解析错误");
        }
        //获取店铺经纬值
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lng = location.getString("lng");
        String lat = location.getString("lat");
        String shopLatLng = lat +","+lng;
        //获取用户地址经纬值
        jsonObject = JSONObject.parseObject(end);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("用户地址解析错误");
        }
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lng = location.getString("lng");
        lat = location.getString("lat");
        String userLatLng = lat +","+lng;
        //规划路线
        Map routeParams = new LinkedHashMap<String, String>();
        routeParams.put("origin", shopLatLng);
        routeParams.put("destination", userLatLng);
        routeParams.put("ak", AK);
        routeParams.put("riding_type","1");
        String route = requestGetAK(ridingURL, routeParams);
        System.out.println("------------route--------------");
        System.out.println(route);
        jsonObject = JSONObject.parseObject(route);
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }
        //获得距离
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
        System.out.println("配送距离为："+distance);
        //小于6km可以配送
        if (distance > 6000)
           throw new OrderBusinessException("超出配送距离");
    }
    /**
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为的计算发起请求，否则将请求失败
     */
    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            throw new OrderBusinessException("解析地址失败");
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        return buffer.toString();
    }


}
